<template>
  <div class="audit-logs-container">
    <el-card class="audit-logs-card">
      <template #header>
        <div class="card-header">
          <span>审计日志</span>
        </div>
      </template>
      
      <!-- 筛选条件 -->
      <el-form :model="filterForm" label-width="80px" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="filterForm.start_date"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="filterForm.end_date"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户ID">
              <el-input
                v-model.number="filterForm.user_id"
                placeholder="请输入用户ID"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作类型">
              <el-select
                v-model="filterForm.action_type"
                placeholder="请选择操作类型"
                clearable
                style="width: 100%"
              >
                <el-option label="登录" value="login" />
                <el-option label="登出" value="logout" />
                <el-option label="创建" value="create" />
                <el-option label="更新" value="update" />
                <el-option label="删除" value="delete" />
                <el-option label="生成密钥" value="generate_key" />
                <el-option label="核验" value="verification" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="searchLogs">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 日志列表 -->
      <el-table
        :data="auditLogs"
        stripe
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="user_name" label="用户名" width="120" />
        <el-table-column prop="action_type" label="操作类型" width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getActionTypeTag(row.action_type)"
              effect="plain"
            >
              {{ getActionTypeName(row.action_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="target_type" label="目标类型" width="120" />
        <el-table-column prop="detail" label="详情" show-overflow-tooltip />
        <el-table-column prop="ip_address" label="IP地址" width="150" />
        <el-table-column prop="created_at" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { adminApi } from '@/api/admin'
import type { AuditLog } from '@/types/admin'
import { showError } from '@/utils/message'
import { formatDate } from '@/utils/date'

// 定义筛选表单
const filterForm = reactive({
  start_date: '',
  end_date: '',
  user_id: undefined as number | undefined,
  action_type: ''
})

// 定义分页参数
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 审计日志列表
const auditLogs = ref<AuditLog[]>([])

// 加载状态
const loading = ref(false)

/**
 * 获取操作类型标签样式
 * @param actionType 操作类型
 * @returns Element Plus标签类型
 */
const getActionTypeTag = (actionType: string) => {
  const tagMap: Record<string, string> = {
    login: 'success',
    logout: 'info',
    create: 'primary',
    update: 'warning',
    delete: 'danger',
    generate_key: 'primary',
    verification: 'success'
  }
  return tagMap[actionType] || 'info'
}

/**
 * 获取操作类型名称
 * @param actionType 操作类型
 * @returns 操作类型名称
 */
const getActionTypeName = (actionType: string) => {
  const nameMap: Record<string, string> = {
    login: '登录',
    logout: '登出',
    create: '创建',
    update: '更新',
    delete: '删除',
    generate_key: '生成密钥',
    verification: '核验'
  }
  return nameMap[actionType] || actionType
}

/**
 * 查询审计日志
 */
const searchLogs = async () => {
  try {
    loading.value = true
    
    // 构造查询参数
    const params: any = {
      page: pagination.page,
      size: pagination.size,
      start_date: filterForm.start_date,
      end_date: filterForm.end_date,
      action_type: filterForm.action_type
    }
    
    // 只有当user_id有值时才添加到参数中
    if (filterForm.user_id !== undefined && filterForm.user_id !== null) {
      params.user_id = filterForm.user_id
    }
    
    // 调用API获取审计日志列表
    const response = await adminApi.getAuditLogs(params)
    
    // 由于响应拦截器已经处理了响应格式，这里直接获取数据
    auditLogs.value = response.items || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取审计日志失败:', error)
    showError('获取审计日志失败')
  } finally {
    loading.value = false
  }
}

/**
 * 重置筛选条件
 */
const resetFilters = () => {
  filterForm.start_date = ''
  filterForm.end_date = ''
  filterForm.user_id = undefined
  filterForm.action_type = ''
  pagination.page = 1
  searchLogs()
}

/**
 * 处理分页大小变化
 * @param size 新的分页大小
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  searchLogs()
}

/**
 * 处理当前页变化
 * @param page 新的当前页
 */
const handleCurrentChange = (page: number) => {
  pagination.page = page
  searchLogs()
}

// 组件挂载时加载数据
onMounted(() => {
  searchLogs()
})
</script>

<style scoped>
.audit-logs-container {
  padding: 20px;
}

.audit-logs-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>